package com.whu.exp1jsp.controller;

import com.whu.exp1jsp.dao.CartDAO;
import com.whu.exp1jsp.pojo.CartSt;
import com.whu.exp1jsp.pojo.ProductSt;
import com.whu.exp1jsp.pojo.UserSt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@WebServlet(name = "removeFromCartServlet", value = "/remove-from-cart-servlet")
public class RemoveFromCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("mode", 2);
        HttpSession session = request.getSession();
        Long productId = Long.parseLong(request.getParameter("productId"));
        if (productId == null) {
            request.setAttribute("errorMessage", "商品不存在");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }
        CartDAO cartDAO = new CartDAO();

        UserSt user = session.getAttribute("user") == null ? null : (UserSt) session.getAttribute("user");
        if (user == null){
            request.setAttribute("error", "请先登录");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        CartSt cartSt = new CartSt(user.getUserId(), productId, new Date());
        try {
            cartDAO.deleteCart(user.getUserId(), productId);
        }catch (SQLException e){
            request.setAttribute("errorMessage", "删除购物车失败");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }
        request.setAttribute("successMessage", "删除购物车成功");
        request.getRequestDispatcher("cart-servlet").forward(request, response);

    }
}
